package infomanage.utils;

import java.util.Scanner;

public class CMUtility {
    private static Scanner scanner = new Scanner(System.in);

    public static char readMenuSelection() {
        while (true) {
            char input = readKeyboard(1, false).charAt(0);
            if (input <= '5' && input >= '1') {
                return input;
            } else {
                System.out.println("输入不符合要求！");
            }
        }
    }

    public static char readChar() {
        return readKeyboard(1, false).charAt(0);
    }

    public static char readChar(char defaultValue) {
        String input = readKeyboard(1, true);
        return input.length() == 0 ? defaultValue : input.charAt(0);
    }

    public static int readInt() {
        return Integer.parseInt(readKeyboard(2, false));
    }

    public static int readInt(int defaultValue) {
        String input = readKeyboard(2, true);
        return input.length() == 0 ? defaultValue : Integer.parseInt(input);
    }

    public static String readString(int limit) {
        return readKeyboard(limit, false);
    }

    public static String readString(int limit, String defaultValue) {
        String input = readKeyboard(limit, true);
        return input.length() == 0 ? defaultValue : input;
    }

    public static char readConfirmSelection() {
        while (true) {
            char input = readKeyboard(1, false).toUpperCase().charAt(0);
            if (input == 'Y' || input == 'N') {
                return input;
            } else {
                System.out.println("输入不符合要求！");
            }
        }
    }


    private static String readKeyboard(int limit, boolean blankReturn) {
        while (true) {
            String input = scanner.nextLine();
            if (input.length() > limit) {
                System.out.println("长度太长！");
            } else if (input.length() == 0 && !blankReturn) {
                System.out.println("长度太短！");
            } else {
                return input;
            }
        }
    }

}
